using System;
using System.Collections.Generic;
using System.Linq;
using CPlatePrintSys.Domain.Models;
using Prism.Mvvm;

namespace CPlatePrintSys.Win.ViewModels
{
    /// <summary>
    /// 合并后的PlateAnnotationInfo的UI绑定ViewModel
    /// </summary>
    public class MergedPlateAnnotationInfoViewModel : BindableBase
    {
        private PlateAnnotationInfoViewModel _primaryRecord;
        private List<PlateAnnotationInfoViewModel> _allRecords;
        private List<int> _originalIds; // 保存原始ID列表
        private bool _isUpdatingSelection = false; // 防止循环更新的标志

        public MergedPlateAnnotationInfoViewModel(PlateAnnotationInfoViewModel primaryRecord, List<PlateAnnotationInfoViewModel> allRecords)
        {
            _primaryRecord = primaryRecord ?? throw new ArgumentNullException(nameof(primaryRecord));
            _allRecords = allRecords ?? new List<PlateAnnotationInfoViewModel>();
            _originalIds = _allRecords.Select(x => x.Id).ToList();
            
            // 初始化选择状态
            _isSelected = _primaryRecord.IsSelected;
        }

        // 合并后的显示ID（重新排序，连续递增）
        public int MergedId { get; set; }

        // 原始ID列表（用于调试和显示）
        public string OriginalIds => string.Join(",", _originalIds);

        // 是否包含多个原始记录
        public bool IsMerged => _allRecords.Count > 1;

    // 合并记录数量
    public int MergedCount => _allRecords.Count;

    // 是否需要合并显示样式
    public bool NeedsMergedDisplay => _allRecords.Count > 1;

        // 选择状态（同步所有记录）
        private bool _isSelected;
        public bool IsSelected
        {
            get => _isSelected;
            set
            {
                if (SetProperty(ref _isSelected, value))
                {
                    // 防止循环更新
                    if (_isUpdatingSelection)
                        return;

                    _isUpdatingSelection = true;
                    try
                    {
                        // 只在值真正改变时才同步到原始记录
                        if (_primaryRecord != null && _primaryRecord.IsSelected != value)
                        {
                            _primaryRecord.IsSelected = value;
                            // 同步所有合并记录的选择状态
                            foreach (var record in _allRecords)
                            {
                                if (record.IsSelected != value)
                                {
                                    record.IsSelected = value;
                                }
                            }
                        }
                    }
                    finally
                    {
                        _isUpdatingSelection = false;
                    }
                    
                    // 触发选择状态变化事件
                    OnSelectionChanged();
                }
            }
        }

        /// <summary>
        /// 选择状态改变事件
        /// </summary>
        public event Action SelectionChanged;

        /// <summary>
        /// 触发选择状态改变事件
        /// </summary>
        private void OnSelectionChanged()
        {
            SelectionChanged?.Invoke();
        }

    // 所有属性都从PrimaryRecord获取（显示主记录的信息）
    public int Id => _primaryRecord.Id;
    
    // 合并显示属性 - 显示合并后的信息
    
    // 合并单元格效果（单行显示）- 仅选择、编号、处理方式、合并信息
    public LayoutMean LayoutMean => _primaryRecord.LayoutMean;
    public string MergedInfo => _primaryRecord.MergedInfo;
    public string LayoutInfo => _primaryRecord.LayoutInfo;
    
    // 多行显示（垂直堆叠）- 其他所有列
    public string MotherShipNo => GetMergedDisplayValue(x => x.MotherShipNo, "\n");
    public string StreamShipNo => GetMergedDisplayValue(x => x.StreamShipNo, "\n");
    public string LotNo => GetMergedDisplayValue(x => x.LotNo, "\n");
    public string PlateNo => GetMergedDisplayValue(x => x.PlateNo, "\n");
    public string Sequence => GetMergedDisplayValue(x => x.Sequence, "\n");
    public string CNO => GetMergedDisplayValue(x => x.CNO, "\n");
    public string DesignSpecCls => GetMergedDisplayValue(x => x.DesignSpecCls, "\n");
    public string DesignSpecThickness => GetMergedDisplayValue(x => x.DesignSpecThickness.ToString(), "\n");
    public string DesignSpecLength => GetMergedDisplayValue(x => x.DesignSpecLength.ToString(), "\n");
    public string DesignSpecWidth => GetMergedDisplayValue(x => x.DesignSpecWidth.ToString(), "\n");
    public string SheetConsistentNo => GetMergedDisplayValue(x => x.SheetConsistentNo, "\n");
    public string SheetSpecCls => GetMergedDisplayValue(x => x.SheetSpecCls, "\n");
    public string SheetSpecThickness => GetMergedDisplayValue(x => x.SheetSpecThickness.ToString(), "\n");
    public string SheetSpecLength => GetMergedDisplayValue(x => x.SheetSpecLength.ToString(), "\n");
    public string SheetSpecWidth => GetMergedDisplayValue(x => x.SheetSpecWidth.ToString(), "\n");
    public string PlanUsedDate => GetMergedDisplayValue(x => x.PlanUsedDate?.ToString("yyyy-MM-dd") ?? "", "\n");
    public string IsAnnotationGenerated => GetMergedDisplayValue(x => x.IsAnnotationGenerated ? "是" : "否", "\n");
    public string DesignDrawingPath => GetMergedDisplayValue(x => x.DesignDrawingPath, "\n");
    public string AnnotationDrawingPath => GetFirstValidAnnotationPath();
    public string SourceType => GetMergedDisplayValue(x => x.SourceType.ToString(), "\n");
    
    // 用于命令判断的布尔属性
    public bool HasAnnotationGenerated => _allRecords.Any(x => x.IsAnnotationGenerated);

    /// <summary>
    /// 获取合并显示值
    /// </summary>
    private string GetMergedDisplayValue(Func<PlateAnnotationInfoViewModel, string> selector, string separator)
    {
        if (_allRecords.Count <= 1)
        {
            return selector(_primaryRecord);
        }

        // 显示所有记录的值，包括重复的，确保多行显示
        var values = _allRecords.Select(selector).ToList();
        return string.Join(separator, values);
    }

        // 获取所有原始数据（用于后续操作）
        public List<PlateAnnotationInfo> GetAllOriginalData()
        {
            return _allRecords.Select(vm => vm.OriginalData).ToList();
        }

        // 获取主记录的原始数据
        public PlateAnnotationInfo GetPrimaryOriginalData()
        {
            return _primaryRecord.OriginalData;
        }

        /// <summary>
        /// 从MergedPlateAnnotationInfoViewModel列表获取选中的原始数据
        /// </summary>
        public static List<PlateAnnotationInfo> GetSelectedOriginalData(
            IEnumerable<MergedPlateAnnotationInfoViewModel> mergedViewModels)
        {
            var selectedData = new List<PlateAnnotationInfo>();
            foreach (var mergedVm in mergedViewModels)
            {
                if (mergedVm.IsSelected)
                {
                    selectedData.AddRange(mergedVm.GetAllOriginalData());
                }
            }
            return selectedData;
        }

        /// <summary>
        /// 获取第一条有效的标注图纸路径
        /// </summary>
        private string GetFirstValidAnnotationPath()
        {
            // 查找第一条非空的标注图纸路径
            var firstPath = _allRecords
                .Where(x => !string.IsNullOrEmpty(x.AnnotationDrawingPath))
                .Select(x => x.AnnotationDrawingPath)
                .FirstOrDefault();

            return firstPath ?? string.Empty;
        }
    }
}
